/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package com.moon.admin.sys.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.moon.admin.framework.secure.annotation.FormRepeat;
import com.moon.admin.framework.secure.annotation.PreAuth;
import com.moon.admin.framework.springmvc.domain.R;
import com.moon.admin.framework.syslog.annotation.SysLog;
import com.moon.admin.framework.util.ToolUtils;
import com.moon.admin.sys.entity.SysMenuEntity;
import com.moon.admin.sys.service.SysMenuService;

/**
 * 菜单
 * @author ninglong
 */
@RestController
@RequestMapping(value="sysMenu")
public class SysMenuController {
	
	@Autowired
	private SysMenuService menuService;
	
    @GetMapping("/list")
    public R<List<SysMenuEntity>> list(){
        List<SysMenuEntity> menuList = menuService.getSysMenuList(true);
        return R.success(menuList);
    }
    
    /**
     * 获取系统所有菜单不包括按扭
     */
    @GetMapping("/getAllMenuNotButton")
    public R<List<SysMenuEntity>> getAllMenuNotButton(){
    	return R.success(menuService.getSysMenuList(false));
    }
    
    @PostMapping("/save")
    @PreAuth("sys_menu_add")
    @FormRepeat
    @SysLog(mod="菜单管理",fun="保存菜单")
    public R<Boolean> save(@RequestBody SysMenuEntity menuEntity){
    	if(ToolUtils.isEmpty(menuEntity.getParentId())){
    		menuEntity.setParentId(0);
    	}
    	if(menuEntity.getParentId()==0){
			SysMenuEntity parentSysMenu = menuService.getById(menuEntity.getParentId());
			menuEntity.setModuleId(parentSysMenu.getModuleId());
		}
    	menuService.saveOrUpdate(menuEntity);
        return R.success();
    }
    
	@GetMapping(value = "removeById")
	@PreAuth("sys_menu_remove")
	@SysLog(fun="菜单管理",mod="删除菜单")
	@FormRepeat
	public R<Void> removeById(Integer id) {
		if(ToolUtils.isNull(id)) {
			return R.fail("请选择要删除的菜单");
		}
		int childCount = menuService.count(Wrappers.<SysMenuEntity>lambdaQuery().eq(SysMenuEntity::getParentId, id));
		if(childCount>0) {
			return R.fail("该菜单下还有子级菜单，不能删除");
		}
		return R.status(menuService.removeById(id));
	}
}